import 'package:flutter/material.dart';

class LJStarRating extends StatefulWidget {
  final double rating;
  final double maxRating;
  final int count;
  final double size;
  final Color unSelectedColor;
  final Color selectedColor;
  final Widget unSelectedImage;
  final Widget selectedImage;

  LJStarRating({
    @required this.rating,
    this.maxRating = 10,
    this.size = 30,
    this.count = 5,
    this.unSelectedColor = const Color(0xffbbbbbb),
    this.selectedColor = const Color(0xffff0000),
    Widget unSelectedImage,
    Widget selectedImage
  }): unSelectedImage = unSelectedImage ?? Icon(Icons.star_border,color: unSelectedColor, size:size,),
        selectedImage = selectedImage ?? Icon(Icons.star,color: selectedColor, size:size,);

  @override
  _LJStarRatingState createState() => _LJStarRatingState();
}

class _LJStarRatingState extends State<LJStarRating> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Row(
            mainAxisSize: MainAxisSize.min,
            children: buildUnSelectedStar()
        ),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: buildSelectedStar(),
        )
      ],
    );
  }
  List<Widget> buildUnSelectedStar(){
    return List.generate(widget.count, (index){
      return widget.unSelectedImage;
    });
  }
  List<Widget> buildSelectedStar(){
    //创建stars
    List<Widget> stars = [];
    final star = widget.selectedImage;
    //计算满的个数
    double oneValue = widget.maxRating / widget.count;
    int entireCount = (widget.rating / oneValue).floor();
    for(var i = 0; i < entireCount; i++){
      stars.add(star);
    }
    // 计算多出部分 (widget.rating / oneValue - entireCount) * widget.size;
    double leftWidth =  (widget.rating / oneValue - entireCount) * widget.size;
    final halfSatr = ClipRect(
      clipper: LJStarClipper(leftWidth),
      child: star,
    );
    stars.add(halfSatr);

    if(stars.length > widget.count){
      return stars.sublist(0,widget.count);
    }

    return stars;
  }
}

class LJStarClipper extends CustomClipper<Rect> {
  double width;
  LJStarClipper(this.width);

  @override
  Rect getClip(Size size) {
    return Rect.fromLTRB(0, 0, width, size.height);
  }
  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return true;
  }
}
